package it.polimi.traveldream.entity;

import it.polimi.traveldream.dto.GiftListElementDTO;
import it.polimi.traveldream.dto.PaidDTO;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * The persistent class for the giftlistelement database table.
 * 
 */
@Entity
@Table(name = "giftlistelement")
@NamedQuery(name = GiftlistElement.FIND_ALL, query = "SELECT g FROM GiftlistElement g WHERE g.user = :user")
public class GiftlistElement implements Serializable {
	private static final long serialVersionUID = 1L;

	public static final String FIND_ALL = "GiftlistElement.findAll";

	@EmbeddedId
	private GiftlistElementPK id;

	@ManyToOne
	@JoinColumn(name = "user", nullable = false)
	private Customer user;

	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "cartpackage", nullable = false)
	private CartPackage cartpackage;

	@OneToMany(cascade = CascadeType.ALL, mappedBy = "giftlistElement")
	private List<Paid> paid;

	public GiftlistElement() {
		this.setId(new GiftlistElementPK());
	}

	public GiftlistElement(GiftListElementDTO elementDTO) {
		this.setCartpackage(new CartPackage(elementDTO.getCartPackage()));

		for (PaidDTO paid : elementDTO.getPaid()) {
			this.addPaid(new Paid(paid));
		}
	}

	public GiftListElementDTO convertToDTO() {
		GiftListElementDTO elementDTO = new GiftListElementDTO();
		elementDTO.setCartPackage(this.getCartpackage().convertToDTO());
		for (Paid paid : this.getPaid()) {
			elementDTO.addPaid(paid.convertToDTO());
		}
		return elementDTO;
	}

	public GiftlistElementPK getId() {
		return this.id;
	}

	public void setId(GiftlistElementPK id) {
		this.id = id;
	}

	public Customer getUser() {
		return this.user;
	}

	public void setUser(Customer user) {
		this.user = user;
	}

	public CartPackage getCartpackage() {
		return this.cartpackage;
	}

	public void setCartpackage(CartPackage cartpackage) {
		this.setPaid(new ArrayList<Paid>());
		this.addPaid(new Paid(cartpackage.getGoing(), 0));
		this.addPaid(new Paid(cartpackage.getBack(), 0));
		this.addPaid(new Paid(cartpackage.getAccomodation(), 0));
		for (Schedule schedule : cartpackage.getSchedule()) {
			this.addPaid(new Paid(schedule.getActivity(), 0));
		}
		this.cartpackage = cartpackage;
	}

	public List<Paid> getPaid() {
		return this.paid;
	}

	public void setPaid(List<Paid> paid) {
		this.paid = paid;
	}

	public boolean addPaid(Paid paid) {
		paid.setGiftlistElement(this);
		return this.getPaid().add(paid);
	}

	public boolean removePaid(Paid paid) {
		return this.getPaid().remove(paid);
	}

}